package admin

import (
	"exercise/application/yiran/app/libs"
	"exercise/application/yiran/app/model"
	"exercise/application/yiran/app/request/adminRequest"
	"fmt"
	"github.com/gin-gonic/gin"
)

type roomService struct{}

func (*roomService) List(ctx *gin.Context, request *adminRequest.RoomListRequest) (map[string]interface{}, error) {
	schoolId, _ := ctx.Get("schoolId")
	list := make([]model.RoomToJzwFloor, 0)
	paging := model.Paging{}
	paging.Page = request.Page
	paging.PageSize = request.PageSize

	total, err := model.NewDb("").FindAllAndCount(&list, "school_id = ? AND room_name LIKE ?", []interface{}{schoolId, "%" + request.Keyword + "%"}, model.OrderOrGroup{}, paging, []string{"Jzw", "Floor"})

	if err != nil {
		return nil, fmt.Errorf("暂无数据：%w", err)
	}

	return map[string]interface{}{
		"list":  list,
		"total": total,
	}, err
}

func (*roomService) Add(ctx *gin.Context, request *adminRequest.AddRoomRequest) (id int64, err error) {

	schoolId, _ := ctx.Get("schoolId")
	room := new(model.Room)

	room.RoomName = request.RoomName
	room.RoomNumber = request.RoomNumber
	room.FloorId = request.FloorId
	room.JzwId = request.JzwId
	room.SeatTotal = request.SeatTotal

	room.SchoolId = schoolId.(int64)
	room.CreateTime = libs.CurrentTime()

	err = model.NewDb("").InsertRecord(room)
	if err != nil {
		return id, err
	}

	return room.Id, nil
}

func (*roomService) Edit(request *adminRequest.EditRoomRequest) error {
	room := new(model.Room)
	err := model.NewDb("").FindOne(room, "id = ? ", []interface{}{request.Id}, "*", []string{})
	if err != nil {
		return err
	}

	room.RoomName = request.RoomName
	room.RoomNumber = request.RoomNumber
	room.FloorId = request.FloorId
	room.JzwId = request.JzwId
	room.SeatTotal = request.SeatTotal

	err = model.NewDb("").SaveRecord(room)
	if err != nil {
		return err
	}
	return nil
}

func (*roomService) Detail(ctx *gin.Context) (res interface{}, err error) {
	id := ctx.Param("id")
	room := new(model.RoomToJzwFloor)
	err = model.NewDb("").FindOne(room, "id = ? ", []interface{}{id}, "*", []string{"Jzw", "Floor"})
	if err != nil {
		return nil, fmt.Errorf("数据异常：%w", err)
	}
	return room, err
}

func (*roomService) Deleted(ctx *gin.Context) error {
	id := ctx.Param("id")
	jzw := new(model.Room)
	err := model.NewDb("").DeleteRecord(jzw, "id = ?", []interface{}{id})
	return err
}

func NewRoomService() *roomService {
	return &roomService{}
}
